from flask import Blueprint, request, render_template, session, redirect
from app.models.TaskModel import TaskModel
from app.services import *
import time

task = Blueprint('project', __name__, url_prefix='/project')


@task.before_request
def before_auth():
    ...
    from_url = request.base_url
    if not UserAuth.isLogin():
        return redirect('/user/login?from={url}'.format(url=from_url))


# 任务列表读取
@task.route('/list', methods=['GET', 'POST'])
def task_list():
    rm = request.method
    params = utils.getParams(request)
    page = int(params.get('page', 1))
    limit = int(params.get('limit', 10))
    isadmin = session.get('userinfo', {}).get('isadmin', False)
    name = session.get('userinfo', {}).get('name')
    search_type = params.get('search_type')
    search_text = params.get('search_text')
    if isadmin == 1:
        isadmin = 'true'
    else:
        isadmin = 'false'
    if rm == 'GET':
        return render_template('component/table/reload.html', isadmin=isadmin, name=name)
    elif rm == 'POST':
        search_rule = {
            'uuid': TaskModel.uuid,
            'title': TaskModel.title,
            'found': TaskModel.found,
            'people': TaskModel.people
        }
        if search_type in search_rule:
            filters = {
                search_rule[search_type].like(f'%{search_text}%')
            }
        else:
            filters = {}
        res = TaskModel.getPageList(filters=filters, order='status asc', page=page, limit=limit)

        return m(
            status=True,
            code=0,
            count=res['count'],
            total=res['total'],
            data=res['data']
        )
    else:
        return 'error'


# 任务创建
@task.route('/created', methods=['GET', 'POST'])
def task_created():
    rm = request.method
    if rm == 'GET':
        return render_template('project/created.html')
    elif rm == 'POST':
        return 'from'
    else:
        return 'Bad Request Methods'


# 任务浏览
@task.route('/view/<string:uuid>', methods=['GET'])
def task_view(uuid):
    filters = {TaskModel.uuid == uuid}
    try:
        rows = TaskModel.getTask(filters=filters)
    except AttributeError as err:
        return '加载失败了哦~重新打开一下看看'
    return render_template('project/view.html', rows=rows, timestampTodatetime=utils.timestampTodatetime)


# 任务跳转
@task.route('/go/<string:uuid>', methods=['GET'])
def task_go(uuid):
    filters = {TaskModel.uuid == uuid}
    rows = TaskModel.getTask(filters=filters)
    if rows is None:
        return render_template('error.html', message='任务无效！', url='/home')
    elif not rows.get('onlineword', False):
        return render_template('error.html', message='找不到该任务的在线文档！', url='/home')
    else:
        return redirect(rows.get('onlineword', '/home'))


class utils:

    @staticmethod
    def getParams(req):
        params = req.json or req.form or req.args or {}
        return params

    @staticmethod
    def timestampTodatetime(times):
        try:
            timestamp = int(times)
        except Exception as err:
            return 0
        timeArray = time.localtime(timestamp)
        otherStyleTime = time.strftime("%Y年%m月%d日 %H:%M:%S", timeArray)
        return otherStyleTime
